package com.chenbei.common.service.impl;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.chenbei.common.constants.CacheKeys;
import com.chenbei.common.service.ICaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CaptchaService implements ICaptchaService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${captcha.type}")
    private String type;

    @Value("${captcha.width}")
    private int width;

    @Value("${captcha.height}")
    private int height;

    @Value("${captcha.expire}")
    private int expire;

    @Override
    public AbstractCaptcha generate(String key) {
        AbstractCaptcha captcha;
        switch (type) {
            case "shear":
                captcha = CaptchaUtil.createShearCaptcha(width, height);
                break;
            case "circle":
                captcha = CaptchaUtil.createCircleCaptcha(width, height);
                break;
            default:
                captcha = CaptchaUtil.createLineCaptcha(width, height);
        }
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        captcha.setGenerator(randomGenerator);
        captcha.createCode();

        // 存入redis
        String code = captcha.getCode();
        stringRedisTemplate.opsForValue().set(getCacheKey(key), code, expire, TimeUnit.SECONDS);
        return captcha;
    }

    @Override
    public boolean verify(String key, String captchaValue) {
        String cacheCaptchaValue = getValue(key);
        if (StrUtil.isNotBlank(captchaValue)) {
            if (captchaValue.equals(cacheCaptchaValue)) {
                stringRedisTemplate.delete(key);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public String getValue(String key) {
        return stringRedisTemplate.opsForValue().get(getCacheKey(key));
    }

    //获取验证码缓存Key
    private String getCacheKey(String key) {
        return CacheKeys.VERIFICATION_CODE_CACHE_KEY + key;
    }
}
